const express = require("express");
const router = express.Router();
const { success, failure } = require("../utils/response");
const { Chapters, Course, Category, User } = require("../models");
const { NotFound } = require("http-errors");
const { Op } = require("sequelize");

/**
 * 查询章节详情
 * GET /chapters/:id
 */
router.get("/:id", async (req, res) => {
  try {
    // 查询章节详情
    const { id } = req.params;
    const condition = {
      attributes: { exclude: ["CourseId"] },
      // include 是指包含某些实体类
      include: [
        {
          model: Course,
          attributes: ["id", "name"],
          as: "course",
          include: [
            {
              model: Category,
              attributes: ["id", "name"],
              as: "category",
            },
            {
              model: User,
              attributes: ["id", "username", "nickname", "avatar", "company"],
              as: "user",
            },
          ],
        },
      ],
    };

    const chapter = await Chapters.findByPk(id, condition);
    if (!chapter) {
      throw new NotFound("章节不存在。");
    }

    // 查询同属一个课程的所有章节
    const chapters = await Chapters.findAll({
      where: {
        courseId: chapter.courseId,
      },
      order: [
        ["rank", "ASC"],
        ["id", "DESC"],
      ],
      // 查询时排除某些字段
      attributes: { exclude: ["courseId"] },
      ...condition,
    });
    success(res, "获取章节详情成功。", { chapter, chapters });
  } catch (error) {
    failure(res, error);
  }
});

router.get("/promise/:id", async (req, res) => {
  try {
    const { id } = req.params;

    // 查询章节
    const chapter = await Chapter.findByPk(id, {
      attributes: { exclude: ["CourseId"] },
    });
    if (!chapter) {
      throw new NotFound(`ID:${id}的章节未找到。`);
    }

    // 查询章节关联的课程
    const course = await chapter.getCourse({
      attributes: ["id", "name", "userId"],
    });

    // 查询课程关联的用户和同属于一个课程的所有章节
    const [user, chapters] = await Promise.all([
      // 查询课程关联的用户
      course.getUser({
        // 查询时包含某些字段
        attributes: ["id", "username", "nickname", "avatar", "company"],
      }),

      // 同属一个课程的所有章节
      Chapter.findAll({
        attributes: { exclude: ["CourseId", "content"] },
        where: { courseId: chapter.courseId },
        order: [
          ["rank", "ASC"],
          ["id", "DESC"],
        ],
      }),
    ]);
    success(res, "查询章节成功", { chapter, course, user, chapters });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
